import { API_TransmitUrl } from './baseUrl'

const parseUrl = (str) => {//JS正则表达式解析URL(协议/域名/端口/路径/参数/锚点)

    if (!parseUrl || !parseUrl.options) {
        parseUrl.options = {
            strictMode: false,
            key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
            q: {
                name: "queryKey",
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            },
            parser: {
                strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
                loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
            }
        };
    }

    if (!str) {
        return '';
    }

    var o = parseUrl.options,
        m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
}
const transmitUrlToVisit = (url, baseUrl = API_TransmitUrl) => {
    const { protocol = 'http', host = '', port = '', relative = '' } = parseUrl(url)
    return `${baseUrl}${protocol == 'https' ? '/https' : protocol == 'wss' ? 'wss' : ''}/host${host}/port${port}${relative}`
}
export default {
    parseUrl,
    transmitUrlToVisit,
}
